import Vue from 'vue'
import { login, logout, phoneLogin } from "@/api/login"
import { ACCESS_TOKEN, USER_NAME,USER_INFO,USER_AUTH,SYS_BUTTON_AUTH, UI_CACHE_DB_DICT_DATA } from "@/store/mutation-types"
import { welcome } from "@/utils/util"
import { queryPermissionsByUser } from '@/api/api'
import { getAction } from '@/api/manage'

const user = {
  state: {
    token: '',
    username: '',
    realname: '',
    welcome: '',
    avatar: '',
    permissionList: [],
    info: {}
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_NAME: (state, { username, realname, welcome }) => {
      state.username = username
      state.realname = realname
      state.welcome = welcome
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_PERMISSIONLIST: (state, permissionList) => {
      state.permissionList = permissionList
    },
    SET_INFO: (state, info) => {
      state.info = info
    },
  },

  actions: {
    // CAS验证登录
    ValidateLogin({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        getAction("/cas/client/validateLogin",userInfo).then(response => {
          console.log("----cas 登录--------",response);
          if(response.success){
            const result = response.result
            const userInfo = result.userInfo
            Vue.ls.set(ACCESS_TOKEN, result.token, 7 * 24 * 60 * 60 * 1000)
            Vue.ls.set(USER_NAME, userInfo.username, 7 * 24 * 60 * 60 * 1000)
            Vue.ls.set(USER_INFO, userInfo, 7 * 24 * 60 * 60 * 1000)
            commit('SET_TOKEN', result.token)
            commit('SET_INFO', userInfo)
            commit('SET_NAME', { username: userInfo.username,realname: userInfo.realname, welcome: welcome() })
            commit('SET_AVATAR', userInfo.avatar)
            resolve(response)
          }else{
            resolve(response)
          }
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 登录
    Login({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        // 绕过登录
        login(userInfo).then(response => {
          if(response.code =='200'){
            const result = response.result
            const userInfo = result.userInfo
            Vue.ls.set(ACCESS_TOKEN, result.token, 7 * 24 * 60 * 60 * 1000)
            Vue.ls.set(USER_NAME, userInfo.username, 7 * 24 * 60 * 60 * 1000)
            Vue.ls.set(USER_INFO, userInfo, 7 * 24 * 60 * 60 * 1000)
            Vue.ls.set(UI_CACHE_DB_DICT_DATA, result.sysAllDictItems, 7 * 24 * 60 * 60 * 1000)
            commit('SET_TOKEN', result.token)
            commit('SET_INFO', userInfo)
            commit('SET_NAME', { username: userInfo.username,realname: userInfo.realname, welcome: welcome() })
            commit('SET_AVATAR', userInfo.avatar)
            resolve(response)
          }else{
            reject(response)
          }
        }).catch(error => {
          reject(error)
        })
      })
    },
    //手机号登录
    PhoneLogin({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
          phoneLogin(userInfo).then(response => {
          if(response.code =='200'){
        const result = response.result
        const userInfo = result.userInfo
        Vue.ls.set(ACCESS_TOKEN, result.token, 7 * 24 * 60 * 60 * 1000)
        Vue.ls.set(USER_NAME, userInfo.username, 7 * 24 * 60 * 60 * 1000)
        Vue.ls.set(USER_INFO, userInfo, 7 * 24 * 60 * 60 * 1000)
        commit('SET_TOKEN', result.token)
        commit('SET_INFO', userInfo)
        commit('SET_NAME', { username: userInfo.username,realname: userInfo.realname, welcome: welcome() })
        commit('SET_AVATAR', userInfo.avatar)
        resolve(response)
      }else{
        reject(response)
      }
    }).catch(error => {
        reject(error)
      })
    })
    },
    // 获取用户信息
    GetPermissionList({ commit }) {
      return new Promise((resolve, reject) => {
        // queryPermissionsByUser(params).then(response => {
          const menuData = [
            // 新增人员
            {
              "path":"/staffAndWorkers/AddStaffAndWorkers",
              "component":"StaffAndWorkers/AddStaffAndWorkers",
              "route":"1",
              "meta":{
                "keepAlive":false,
                "internalOrExternal":false,
                "title":"新增人员"
              },
              "name":"AddDAddStaffAndWorkersevice",
              "id":"4f16409sdasdef3sdasbbd69c1d8042169d6e2a885e"
            },
            // 新增/编辑设备
            {
              "path":"/deviceInformation/addDevice",
              "component":"DeviceInformation/AddDevice",
              "route":"1",
              "meta":{
                "keepAlive":false,
                "internalOrExternal":false,
                "title":"编辑设备"
              },
              "name":"AddDevice",
              "id":"4f16409sdasdefsdasdaaa3bbd69c1d8042169d6e2a885e"
            },
            // 设置
            {
              "path":"/largeScreenSettings",
              "component":"LargeScreenSettings",
              "route":"1",
              "meta":{
                "keepAlive":false,
                "internalOrExternal":false,
                "title":"设置"
              },
              "name":"LargeScreenSettings",
              "id":"4f16409ef3bbd69c1d8042169d6e2a885e"
            },
            // 文章管理
            {
              "path":"/articleManage",
              "component":"ArticleManage/index",
              "route":"1",
              "meta":{
                "keepAlive":false,
                "internalOrExternal":false,
                "title":"文章管理"
              },
              "name":"ArticleManage",
              "id":"4f16409ef3bbd69c1d804sas69d6e2a885e"
            },
            // 新增编辑文章
            {
              "path":"/articleManage/editArticle",
              "component":"ArticleManage/EditArticle",
              "route":"1",
              "meta":{
                "keepAlive":false,
                "internalOrExternal":false,
                "title":"编辑文章"
              },
              "name":"EditArticle",
              "id":"4f16409ef3bbd69c1d80469d6e2a885e"
            },
            // 链接管理
            {
              "path":"/linkTotal",
              "component":"LinkMan/index",
              "route":"1",
              "meta":{
                "keepAlive":false,
                "internalOrExternal":false,
                "title":"链接管理"
              },
              "name":"LinkTotal",
              "id":"4f16sda409ef3bbd69c1d804sas69d6e2a885e"
            },
            // 轮播图管理
            {
              "path":"/imgMan",
              "component":"ImgMan/index",
              "route":"1",
              "meta":{
                "keepAlive":false,
                "internalOrExternal":false,
                "title":"轮播图管理"
              },
              "name":"ImgMan",
              "id":"4f16sda4sdsad09ef3bbd69c1d804sas69d6e2a885e"
            },
          ]
          if (menuData && menuData.length > 0) {
            //update--begin--autor:qinfeng-----date:20200109------for：JEECG-63 一级菜单的子菜单全部是隐藏路由，则一级菜单不显示------
            menuData.forEach((item, index) => {
              if (item["children"]) {
                let hasChildrenMenu = item["children"].filter((i) => {
                  return !i.hidden || i.hidden == false
                })
                if (hasChildrenMenu == null || hasChildrenMenu.length == 0) {
                  item["hidden"] = true
                }
              }
            })
            console.log(" menu show json ", menuData)
            //update--end--autor:qinfeng-----date:20200109------for：JEECG-63 一级菜单的子菜单全部是隐藏路由，则一级菜单不显示------
            commit('SET_PERMISSIONLIST', menuData)
          } else {
            reject('getPermissionList: permissions must be a non-null array !')
          }
          resolve(menuData)
      //   }).catch(error => {
      //     reject(error)
      //   })
      })
    },

    // 登出
    Logout({ commit, state }) {
      return new Promise((resolve) => {
        commit('SET_TOKEN', '')
        commit('SET_PERMISSIONLIST', [])
        Vue.ls.remove(ACCESS_TOKEN)
        Vue.ls.remove(UI_CACHE_DB_DICT_DATA)
        //console.log('logoutToken: '+ logoutToken)
        resolve()
      })
    },

  }
}

export default user